#include <stdio.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <getopt.h>
#include <iptables.h>

#include <stdlib.h>
#include <string.h>

#include "ipt_ipcontext.h"

/* This function is called from the ipcontext module's parse function 	    */
/* The function checks flag and it's value (if the flag should get value    */
/* The function created struct ipt_context_info* info which will be passed  */
/* to the kernel mode to the match function. 				    */
/* In addion the *flags argument will be passed to the final_check function */
int parseArguments(int c, char **argv, unsigned int *flags, struct ipt_entry_match **match)
{
	struct ipt_context_info* info = (struct ipt_context_info*)((*match)->data);

	switch (c) {
		case '1': /* --ipcontext_port port_num */
			info->port   = atoi (optarg);
			info->flags |= IPCONTEXT_PORT;
			*flags      |= IPCONTEXT_PORT; 
			break;
		case '2': /* --ipcontext_protocol protocol */
			snprintf(info->protocol, PROTOCOL_SIZE, "%s", optarg);
			info->flags |= IPCONTEXT_PROTOCOL;
			*flags      |= IPCONTEXT_PROTOCOL; 
			break;
		case '3': /* --ipcontext_log */
			info->flags |= IPCONTEXT_LOG;
			*flags      |= IPCONTEXT_LOG; 
			break;
		case '4': /* --ipcontext_regexp REGEXP */
			snprintf ( info->regular_exp,REGEXP_SIZE, "%s", optarg );
			info->flags |= IPCONTEXT_REGEXP;
			*flags      |= IPCONTEXT_REGEXP; 
			break;
		case '5': /* --ipcontext_dir 1 */
			if (atoi(optarg) == 1) { 
				info->flags |= IPCONTEXT_IN;
			} 
			break;		
		default:
			return 0; /* undefined flag */
	};
	return 1;  /* the flag was recognized */
} 

/* final_check_args checks for the legality of the flags				 */
/* each rule must have port, protocol, regexp, if one of them wasn't define in the rule */
/* then the rule isn't legal and the missing flags are printed out to the screeen 	*/
void final_check_Args(unsigned int flags)
{
	char err[200];
	if ((flags & IPCONTEXT_PORT) 
		&& (flags & IPCONTEXT_PROTOCOL)
		&& (flags & IPCONTEXT_REGEXP)) {
		return;	/* the rule has port, protocol and regexp */
	}

	/* the rule doesn't have all the flags */
	snprintf ( err, 200 , "ipt_context:final_check:	 Invalid Params! %s %s %s ",
	                       ( flags & IPCONTEXT_PORT )    ? " " : "\n --ipcontext_port   <port> is missing" ,
	                       ( flags & IPCONTEXT_REGEXP )  ? " " : "\n --ipcontext_regexp <regexp>is missing" ,
	                       ( flags & IPCONTEXT_PROTOCOL )? " " : "\n --ipcontext_protocol <protocol> is missing" );
	#ifndef TESTING_MODE
		exit_error(PARAMETER_PROBLEM, err);
	#endif
}
